<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      python/常用模块/8-logging模块 | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>python/常用模块/8-logging模块</h2>



  <p class="post-date">2020-12-21</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h1 id="一、低配logging"><a href="#一、低配logging" class="headerlink" title="一、低配logging"></a>一、低配logging</h1><p>日志总共分为以下五个级别，这个五个级别自下而上进行匹配 debug–&gt;info–&gt;warning–&gt;error–&gt;critical，默认最低级别为warning级别。</p>
<p><img src="https://tva1.sinaimg.cn/large/0081Kckwgy1glwz3dwtu7j30j60asgmb.jpg" alt="73logging模块-日记.jpg"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">import logging</span><br><span class="line"></span><br><span class="line">logging.debug(&#39;调试信息&#39;)</span><br><span class="line">logging.info(&#39;正常信息&#39;)</span><br><span class="line">logging.warning(&#39;警告信息&#39;)</span><br><span class="line">logging.error(&#39;报错信息&#39;)</span><br><span class="line">logging.critical(&#39;严重错误信息&#39;)</span><br></pre></td></tr></table></figure>



<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">WARNING:root:警告信息</span><br><span class="line">ERROR:root:报错信息</span><br><span class="line">CRITICAL:root:严重错误信息</span><br></pre></td></tr></table></figure>

<p>v1版本无法指定日志的级别；无法指定日志的格式；只能往屏幕打印，无法写入文件。因此可以改成下述的代码。</p>
<h2 id="1-2-v2"><a href="#1-2-v2" class="headerlink" title="1.2 v2"></a>1.2 v2</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">import logging</span><br><span class="line"></span><br><span class="line"># 日志的基本配置</span><br><span class="line"></span><br><span class="line">logging.basicConfig(filename&#x3D;&#39;access.log&#39;,</span><br><span class="line">                    format&#x3D;&#39;%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s&#39;,</span><br><span class="line">                    datefmt&#x3D;&#39;%Y-%m-%d %H:%M:%S %p&#39;,</span><br><span class="line">                    level&#x3D;10)</span><br><span class="line"></span><br><span class="line">logging.debug(&#39;调试信息&#39;)  # 10</span><br><span class="line">logging.info(&#39;正常信息&#39;)  # 20</span><br><span class="line">logging.warning(&#39;警告信息&#39;)  # 30</span><br><span class="line">logging.error(&#39;报错信息&#39;)  # 40</span><br><span class="line">logging.critical(&#39;严重错误信息&#39;)  # 50</span><br></pre></td></tr></table></figure>



<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">可在logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为，可用参数有:</span><br><span class="line">    </span><br><span class="line">filename：用指定的文件名创建FiledHandler（后边会具体讲解handler的概念），这样日志会被存储在指定的文件中。</span><br><span class="line">filemode：文件打开方式，在指定了filename时使用这个参数，默认值为“a”还可指定为“w”。</span><br><span class="line">format：指定handler使用的日志显示格式。</span><br><span class="line">datefmt：指定日期时间格式。</span><br><span class="line">level：设置rootlogger（后边会讲解具体概念）的日志级别</span><br><span class="line">stream：用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件，默认为sys.stderr。若同时列出了filename和stream两个参数，则stream参数会被忽略。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">format参数中可能用到的格式化串：</span><br><span class="line"></span><br><span class="line">%(name)s Logger的名字</span><br><span class="line">%(levelno)s 数字形式的日志级别</span><br><span class="line">%(levelname)s 文本形式的日志级别</span><br><span class="line">%(pathname)s 调用日志输出函数的模块的完整路径名，可能没有</span><br><span class="line">%(filename)s 调用日志输出函数的模块的文件名</span><br><span class="line">%(module)s 调用日志输出函数的模块名</span><br><span class="line">%(funcName)s 调用日志输出函数的函数名</span><br><span class="line">%(lineno)d 调用日志输出函数的语句所在的代码行</span><br><span class="line">%(created)f 当前时间，用UNIX标准的表示时间的浮 点数表示</span><br><span class="line">%(relativeCreated)d 输出日志信息时的，自Logger创建以 来的毫秒数</span><br><span class="line">%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒</span><br><span class="line">%(thread)d 线程ID。可能没有</span><br><span class="line">%(threadName)s 线程名。可能没有</span><br><span class="line">%(process)d 进程ID。可能没有</span><br><span class="line">%(message)s用户输出的消息</span><br></pre></td></tr></table></figure>

<p>v2版本不能指定字符编码；只能往文件中打印。</p>
<h2 id="1-3-v3"><a href="#1-3-v3" class="headerlink" title="1.3 v3"></a>1.3 v3</h2><p>logging模块包含四种角色：logger、Filter、Formatter对象、Handler</p>
<ol>
<li>logger：产生日志的对象</li>
<li>Filter：过滤日志的对象</li>
<li>Formatter对象：可以定制不同的日志格式对象，然后绑定给不同的Handler对象使用，以此来控制不同的Handler的日志格式</li>
<li>Handler：接收日志然后控制打印到不同的地方，FileHandler用来打印到文件中，StreamHandler用来打印到终端</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line">&#39;&#39;&#39;</span><br><span class="line">critical&#x3D;50</span><br><span class="line">error &#x3D;40</span><br><span class="line">warning &#x3D;30</span><br><span class="line">info &#x3D; 20</span><br><span class="line">debug &#x3D;10</span><br><span class="line">&#39;&#39;&#39;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">import logging</span><br><span class="line"></span><br><span class="line"># 1、logger对象：负责产生日志，然后交给Filter过滤，然后交给不同的Handler输出</span><br><span class="line">logger &#x3D; logging.getLogger(__file__)</span><br><span class="line"></span><br><span class="line"># 2、Filter对象：不常用，略</span><br><span class="line"></span><br><span class="line"># 3、Handler对象：接收logger传来的日志，然后控制输出</span><br><span class="line">h1 &#x3D; logging.FileHandler(&#39;t1.log&#39;)  # 打印到文件</span><br><span class="line">h2 &#x3D; logging.FileHandler(&#39;t2.log&#39;)  # 打印到文件</span><br><span class="line">sm &#x3D; logging.StreamHandler()  # 打印到终端</span><br><span class="line"></span><br><span class="line"># 4、Formatter对象：日志格式</span><br><span class="line">formmater1 &#x3D; logging.Formatter(&#39;%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s&#39;,</span><br><span class="line">                               datefmt&#x3D;&#39;%Y-%m-%d %H:%M:%S %p&#39;,)</span><br><span class="line"></span><br><span class="line">formmater2 &#x3D; logging.Formatter(&#39;%(asctime)s :  %(message)s&#39;,</span><br><span class="line">                               datefmt&#x3D;&#39;%Y-%m-%d %H:%M:%S %p&#39;,)</span><br><span class="line"></span><br><span class="line">formmater3 &#x3D; logging.Formatter(&#39;%(name)s %(message)s&#39;,)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 5、为Handler对象绑定格式</span><br><span class="line">h1.setFormatter(formmater1)</span><br><span class="line">h2.setFormatter(formmater2)</span><br><span class="line">sm.setFormatter(formmater3)</span><br><span class="line"></span><br><span class="line"># 6、将Handler添加给logger并设置日志级别</span><br><span class="line">logger.addHandler(h1)</span><br><span class="line">logger.addHandler(h2)</span><br><span class="line">logger.addHandler(sm)</span><br><span class="line"></span><br><span class="line"># 设置日志级别，可以在两个关卡进行设置logger与handler</span><br><span class="line"># logger是第一级过滤，然后才能到handler</span><br><span class="line">logger.setLevel(30)</span><br><span class="line">h1.setLevel(10)</span><br><span class="line">h2.setLevel(10)</span><br><span class="line">sm.setLevel(10)</span><br><span class="line"></span><br><span class="line"># 7、测试</span><br><span class="line">logger.debug(&#39;debug&#39;)</span><br><span class="line">logger.info(&#39;info&#39;)</span><br><span class="line">logger.warning(&#39;warning&#39;)</span><br><span class="line">logger.error(&#39;error&#39;)</span><br><span class="line">logger.critical(&#39;critical&#39;)</span><br></pre></td></tr></table></figure>

<h1 id="二、高配logging"><a href="#二、高配logging" class="headerlink" title="二、高配logging"></a>二、高配logging</h1><p><img src="https://tva1.sinaimg.cn/large/0081Kckwgy1glwz3io9wuj30go0beaac.jpg" alt="73loggin模块-低高配.jpg"></p>
<h2 id="2-1-配置日志文件"><a href="#2-1-配置日志文件" class="headerlink" title="2.1 配置日志文件"></a>2.1 配置日志文件</h2><p><strong>以上三个版本的日志只是为了引出我们下面的日志配置文件</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><span class="line">import os</span><br><span class="line">import logging.config</span><br><span class="line"></span><br><span class="line"># 定义三种日志输出格式 开始</span><br><span class="line">standard_format &#x3D; &#39;[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]&#39; \</span><br><span class="line">                  &#39;[%(levelname)s][%(message)s]&#39;  # 其中name为getLogger()指定的名字；lineno为调用日志输出函数的语句所在的代码行</span><br><span class="line">simple_format &#x3D; &#39;[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s&#39;</span><br><span class="line">id_simple_format &#x3D; &#39;[%(levelname)s][%(asctime)s] %(message)s&#39;</span><br><span class="line"># 定义日志输出格式 结束</span><br><span class="line"></span><br><span class="line">logfile_dir &#x3D; os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  # log文件的目录，需要自定义文件路径 # atm</span><br><span class="line">logfile_dir &#x3D; os.path.join(logfile_dir, &#39;log&#39;)  # C:\Users\oldboy\Desktop\atm\log</span><br><span class="line"></span><br><span class="line">logfile_name &#x3D; &#39;log.log&#39;  # log文件名，需要自定义路径名</span><br><span class="line"></span><br><span class="line"># 如果不存在定义的日志目录就创建一个</span><br><span class="line">if not os.path.isdir(logfile_dir):  # C:\Users\oldboy\Desktop\atm\log</span><br><span class="line">    os.mkdir(logfile_dir)</span><br><span class="line"></span><br><span class="line"># log文件的全路径</span><br><span class="line">logfile_path &#x3D; os.path.join(logfile_dir, logfile_name)  # C:\Users\oldboy\Desktop\atm\log\log.log</span><br><span class="line"># 定义日志路径 结束</span><br><span class="line"></span><br><span class="line"># log配置字典</span><br><span class="line">LOGGING_DIC &#x3D; &#123;</span><br><span class="line">    &#39;version&#39;: 1,</span><br><span class="line">    &#39;disable_existing_loggers&#39;: False,</span><br><span class="line">    &#39;formatters&#39;: &#123;</span><br><span class="line">        &#39;standard&#39;: &#123;</span><br><span class="line">            &#39;format&#39;: standard_format</span><br><span class="line">        &#125;,</span><br><span class="line">        &#39;simple&#39;: &#123;</span><br><span class="line">            &#39;format&#39;: simple_format</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">    &#39;filters&#39;: &#123;&#125;,  # filter可以不定义</span><br><span class="line">    &#39;handlers&#39;: &#123;</span><br><span class="line">        # 打印到终端的日志</span><br><span class="line">        &#39;console&#39;: &#123;</span><br><span class="line">            &#39;level&#39;: &#39;DEBUG&#39;,</span><br><span class="line">            &#39;class&#39;: &#39;logging.StreamHandler&#39;,  # 打印到屏幕</span><br><span class="line">            &#39;formatter&#39;: &#39;simple&#39;</span><br><span class="line">        &#125;,</span><br><span class="line">        # 打印到文件的日志,收集info及以上的日志</span><br><span class="line">        &#39;default&#39;: &#123;</span><br><span class="line">            &#39;level&#39;: &#39;INFO&#39;,</span><br><span class="line">            &#39;class&#39;: &#39;logging.handlers.RotatingFileHandler&#39;,  # 保存到文件</span><br><span class="line">            &#39;formatter&#39;: &#39;standard&#39;,</span><br><span class="line">            &#39;filename&#39;: logfile_path,  # 日志文件</span><br><span class="line">            &#39;maxBytes&#39;: 1024 * 1024 * 5,  # 日志大小 5M  (*****)</span><br><span class="line">            &#39;backupCount&#39;: 5,</span><br><span class="line">            &#39;encoding&#39;: &#39;utf-8&#39;,  # 日志文件的编码，再也不用担心中文log乱码了</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">    &#39;loggers&#39;: &#123;</span><br><span class="line">        # logging.getLogger(__name__)拿到的logger配置。如果&#39;&#39;设置为固定值logger1，则下次导入必须设置成logging.getLogger(&#39;logger1&#39;)</span><br><span class="line">        &#39;&#39;: &#123;</span><br><span class="line">            # 这里把上面定义的两个handler都加上，即log数据既写入文件又打印到屏幕</span><br><span class="line">            &#39;handlers&#39;: [&#39;default&#39;, &#39;console&#39;],</span><br><span class="line">            &#39;level&#39;: &#39;DEBUG&#39;,</span><br><span class="line">            &#39;propagate&#39;: False,  # 向上（更高level的logger）传递</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def load_my_logging_cfg():</span><br><span class="line">    logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置</span><br><span class="line">    logger &#x3D; logging.getLogger(__name__)  # 生成一个log实例</span><br><span class="line">    logger.info(&#39;It works!&#39;)  # 记录该文件的运行状态</span><br><span class="line">    </span><br><span class="line">    return logger</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">if __name__ &#x3D;&#x3D; &#39;__main__&#39;:</span><br><span class="line">    load_my_logging_cfg()</span><br></pre></td></tr></table></figure>

<h2 id="2-2-使用日志"><a href="#2-2-使用日志" class="headerlink" title="2.2 使用日志"></a>2.2 使用日志</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">import time</span><br><span class="line">import logging</span><br><span class="line">import my_logging  # 导入自定义的logging配置</span><br><span class="line"></span><br><span class="line">logger &#x3D; logging.getLogger(__name__)  # 生成logger实例</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def demo():</span><br><span class="line">    logger.debug(&quot;start range... time:&#123;&#125;&quot;.format(time.time()))</span><br><span class="line">    logger.info(&quot;中文测试开始。。。&quot;)</span><br><span class="line">    for i in range(10):</span><br><span class="line">        logger.debug(&quot;i:&#123;&#125;&quot;.format(i))</span><br><span class="line">        time.sleep(0.2)</span><br><span class="line">    else:</span><br><span class="line">        logger.debug(&quot;over range... time:&#123;&#125;&quot;.format(time.time()))</span><br><span class="line">    logger.info(&quot;中文测试结束。。。&quot;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">if __name__ &#x3D;&#x3D; &quot;__main__&quot;:</span><br><span class="line">    my_logging.load_my_logging_cfg()  # 在你程序文件的入口加载自定义logging配置</span><br><span class="line">    demo()</span><br></pre></td></tr></table></figure>

<h1 id="三、Django日志配置文件"><a href="#三、Django日志配置文件" class="headerlink" title="三、Django日志配置文件"></a>三、Django日志配置文件</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br></pre></td><td class="code"><pre><span class="line"># logging_config.py</span><br><span class="line"></span><br><span class="line">LOGGING &#x3D; &#123;</span><br><span class="line">    &#39;version&#39;: 1,</span><br><span class="line">    &#39;disable_existing_loggers&#39;: False,</span><br><span class="line">    &#39;formatters&#39;: &#123;</span><br><span class="line">        &#39;standard&#39;: &#123;</span><br><span class="line">            &#39;format&#39;: &#39;[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]&#39;</span><br><span class="line">                      &#39;[%(levelname)s][%(message)s]&#39;</span><br><span class="line">        &#125;,</span><br><span class="line">        &#39;simple&#39;: &#123;</span><br><span class="line">            &#39;format&#39;: &#39;[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s&#39;</span><br><span class="line">        &#125;,</span><br><span class="line">        &#39;collect&#39;: &#123;</span><br><span class="line">            &#39;format&#39;: &#39;%(message)s&#39;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    &#39;filters&#39;: &#123;</span><br><span class="line">        &#39;require_debug_true&#39;: &#123;</span><br><span class="line">            &#39;()&#39;: &#39;django.utils.log.RequireDebugTrue&#39;,</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">    &#39;handlers&#39;: &#123;</span><br><span class="line">        # 打印到终端的日志</span><br><span class="line">        &#39;console&#39;: &#123;</span><br><span class="line">            &#39;level&#39;: &#39;DEBUG&#39;,</span><br><span class="line">            &#39;filters&#39;: [&#39;require_debug_true&#39;],</span><br><span class="line">            &#39;class&#39;: &#39;logging.StreamHandler&#39;,</span><br><span class="line">            &#39;formatter&#39;: &#39;simple&#39;</span><br><span class="line">        &#125;,</span><br><span class="line">        # 打印到文件的日志,收集info及以上的日志</span><br><span class="line">        &#39;default&#39;: &#123;</span><br><span class="line">            &#39;level&#39;: &#39;INFO&#39;,</span><br><span class="line">            &#39;class&#39;: &#39;logging.handlers.RotatingFileHandler&#39;,  # 保存到文件，自动切</span><br><span class="line">            &#39;filename&#39;: os.path.join(BASE_LOG_DIR, &quot;xxx_info.log&quot;),  # 日志文件</span><br><span class="line">            &#39;maxBytes&#39;: 1024 * 1024 * 5,  # 日志大小 5M</span><br><span class="line">            &#39;backupCount&#39;: 3,</span><br><span class="line">            &#39;formatter&#39;: &#39;standard&#39;,</span><br><span class="line">            &#39;encoding&#39;: &#39;utf-8&#39;,</span><br><span class="line">        &#125;,</span><br><span class="line">        # 打印到文件的日志:收集错误及以上的日志</span><br><span class="line">        &#39;error&#39;: &#123;</span><br><span class="line">            &#39;level&#39;: &#39;ERROR&#39;,</span><br><span class="line">            &#39;class&#39;: &#39;logging.handlers.RotatingFileHandler&#39;,  # 保存到文件，自动切</span><br><span class="line">            &#39;filename&#39;: os.path.join(BASE_LOG_DIR, &quot;xxx_err.log&quot;),  # 日志文件</span><br><span class="line">            &#39;maxBytes&#39;: 1024 * 1024 * 5,  # 日志大小 5M</span><br><span class="line">            &#39;backupCount&#39;: 5,</span><br><span class="line">            &#39;formatter&#39;: &#39;standard&#39;,</span><br><span class="line">            &#39;encoding&#39;: &#39;utf-8&#39;,</span><br><span class="line">        &#125;,</span><br><span class="line">        # 打印到文件的日志</span><br><span class="line">        &#39;collect&#39;: &#123;</span><br><span class="line">            &#39;level&#39;: &#39;INFO&#39;,</span><br><span class="line">            &#39;class&#39;: &#39;logging.handlers.RotatingFileHandler&#39;,  # 保存到文件，自动切</span><br><span class="line">            &#39;filename&#39;: os.path.join(BASE_LOG_DIR, &quot;xxx_collect.log&quot;),</span><br><span class="line">            &#39;maxBytes&#39;: 1024 * 1024 * 5,  # 日志大小 5M</span><br><span class="line">            &#39;backupCount&#39;: 5,</span><br><span class="line">            &#39;formatter&#39;: &#39;collect&#39;,</span><br><span class="line">            &#39;encoding&#39;: &quot;utf-8&quot;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    &#39;loggers&#39;: &#123;</span><br><span class="line">        # logging.getLogger(__name__)拿到的logger配置</span><br><span class="line">        &#39;&#39;: &#123;</span><br><span class="line">            &#39;handlers&#39;: [&#39;default&#39;, &#39;console&#39;, &#39;error&#39;],</span><br><span class="line">            &#39;level&#39;: &#39;DEBUG&#39;,</span><br><span class="line">            &#39;propagate&#39;: True,</span><br><span class="line">        &#125;,</span><br><span class="line">        # logging.getLogger(&#39;collect&#39;)拿到的logger配置</span><br><span class="line">        &#39;collect&#39;: &#123;</span><br><span class="line">            &#39;handlers&#39;: [&#39;console&#39;, &#39;collect&#39;],</span><br><span class="line">            &#39;level&#39;: &#39;INFO&#39;,</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># -----------</span><br><span class="line"># 用法:拿到俩个logger</span><br><span class="line"></span><br><span class="line">logger &#x3D; logging.getLogger(__name__)  # 线上正常的日志</span><br><span class="line">collect_logger &#x3D; logging.getLogger(&quot;collect&quot;)  # 领导说,需要为领导们单独定制领导们看的日志</span><br></pre></td></tr></table></figure></section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/python/%E5%B8%B8%E7%94%A8%E6%A8%A1%E5%9D%97/15-pathlib%E6%A8%A1%E5%9D%97/">
        <span class="nav-arrow">← </span>
        
          python/常用模块/15-pathlib模块
        
      </a>
    
    
      <a class="nav-right" href="/python/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E9%AB%98%E9%98%B6/2-%E5%8F%8D%E5%B0%84(hasattr%E5%92%8Cgetattr%E5%92%8Csetattr%E5%92%8Cdelattr)/">
        
          python/面向对象高阶/2-反射(hasattr和getattr和setattr和delattr)
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#一、低配logging"><span class="toc-nav-text">一、低配logging</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#1-2-v2"><span class="toc-nav-text">1.2 v2</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#1-3-v3"><span class="toc-nav-text">1.3 v3</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#二、高配logging"><span class="toc-nav-text">二、高配logging</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#2-1-配置日志文件"><span class="toc-nav-text">2.1 配置日志文件</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#2-2-使用日志"><span class="toc-nav-text">2.2 使用日志</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#三、Django日志配置文件"><span class="toc-nav-text">三、Django日志配置文件</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/python/常用模块/8-logging模块/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "python/常用模块/8-logging模块",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>